<template>
  <div class="tree-node">
    <div @click="handleClick(node)" :class="{selected: selected}">
      {{
        node.label
      }}
    </div>
    <div class="sub" v-if="hasChildren && isExpanded">
      <TreeNode v-for="item in (node.children || [])" :key="item.label" :node="item" @node-click="handleClick" :selected_id="selected_id"></TreeNode>
    </div>
  </div>
</template>
<script>
export default {
  name: 'TreeNode',
  props: {
    node: Object,
    selected_id: String
  },
  data() {
    return {
      isExpanded: false
    }
  },
  computed: {
    hasChildren() {
      return this.node.children && this.node.children.length > 0
    },
    selected() {
      return this.node.id == this.selected_id
    }
  },
  methods: {
    handleClick(node) {
      if(node.id === this.node.id) {
        this.isExpanded = !this.isExpanded
      }
      this.$emit('node-click', node)
    }
  }
}
</script>
<style lang="less" scoped>
.tree-node {
  width: 100px;
  .sub {
    padding-left: 10px;
  }
  .selected {
    background-color: mediumaquamarine;
  }
}
</style>